truncate table [$temptable1]
insert into [$temptable1] with (HOLDLOCK TABLOCKX)
select D.[$IndexId],
(K.leaf*2-1)+case when Row_number() 
	over (partition by K.leaf Order by [$DataColumn]) <=$Number then 1 else 2 end
from [$temptable2] K with (HOLDLOCK TABLOCKX) inner join [$Datatable] D on K.id =D.[$IndexId]

